<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v3;


use app\api\model\Authority;

use think\Controller;

use think\Request;
use think\Exception;
use app\api\validate;
use  app\api\model\Approval;
use Think\Db;


class MaterialScience extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;


    public function _initialize()
    {
        $this->model = new Authority();

        $this->us = Authority::check(1);

    }


    /**
     * 获取库存列表
     */
    public function Stock_list()
    {
        $data = Request::instance()->post(['type','ok']);
        if ($data['type'] == 0) {
            $custom = db('custom_material')
                ->field('id,company,stock_name,latest_cost,number,created_time,number')
                ->where(['store_id' => $this->us['store_id'], 'status' => 0])
                ->where('number', 'neq', 0)
                ->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 0;
            }
        } else if ($data['type'] == 99) {
            $cust = db('purchase_usage')
                ->field('id,company,stock_name,latest_cost,number,created_time,status,content,remake')
                ->where('type', 1)
                ->where('number', 'neq', 0);
                 if (isset($data['ok']) && $data['ok'] != '') {
                     $cust->where(['status' => 3]);
                 }
            $custom=$cust->where('store_id', $this->us['store_id'])
                ->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 99;
            }
        } else {
            $custom = db('stock')
                ->field('id,company,stock_name,latest_cost,type,class_table')
                ->where('type', $data['type'])
                ->select();
            foreach ($custom as $k => $value) {
                $custom[$k]['number'] = db('routine_usage')
                    ->where('store_id', $this->us['store_id'])
                    ->where('stock_id', $value['id'])
                    ->sum('number');;

            }

        }

        r_date($custom, 200);
    }

    /**
     * 获取库存列表
     */
    public function Stock_list_search()
    {
        $data = Request::instance()->post(['title']);

        $custom_material = [];
        $purchase_usage  = [];
        $routine_usage   = [];
        $custom_material = db('custom_material')
            ->field('id,company,stock_name,latest_cost,number,created_time,number')
            ->where(['store_id' => $this->us['store_id'], 'status' => 0])
            ->where(['stock_name' => ['like', "%{$data['title']}%"]])
            ->where('number', 'neq', 0)
            ->select();
        foreach ($custom_material as $k => $l) {
            $custom_material[$k]['type'] = 0;
        }

        $purchase_usage = db('purchase_usage')
            ->field('id,company,stock_name,latest_cost,number,created_time,status,content,remake')
            ->where('type', 1)
            ->where('number', 'neq', 0)
            ->where('status', 3)
            ->where(['stock_name' => ['like', "%{$data['title']}%"]])
            ->where('store_id', $this->us['store_id'])
            ->select();
        foreach ($purchase_usage as $k => $l) {
            $purchase_usage[$k]['type'] = 99;
        }

        $routine_usage = db('stock')
            ->field('id,company,stock_name,latest_cost,type,class_table')
            ->where(['stock_name' => ['like', "%{$data['title']}%"]])
            ->select();
        foreach ($routine_usage as $k => $value) {
            $routine_usage[$k]['number'] = db('routine_usage')
                ->where('store_id', $this->us['store_id'])
                ->where('stock_id', $value['id'])
                ->sum('number');;

        }

        r_date(array_merge(array_merge($custom_material, $purchase_usage), $routine_usage), 200);
    }


    /**
     * 获取已选列表
     */
    public function get_Material_list()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('material_usage')
            ->where(['order_id' => $data['order_id'], 'types' => $data['type'], 'status' => ['neq', '2']])
            ->field('Material_id,material_name,type,square_quantity,total_price,company,unit_price,created_time,id,status,remake')
            ->order('status asc')
            ->select();


        r_date($material_usage, 200);
    }

    /**
     * 师傅材料审核
     */
    public function get_Material_To_examine()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('material_usage')
            ->where(['id' => $data['id']])
            ->update(['status' => $data['status'], 'remake' => $data['remake']]);
        if($data['status']==2){
            $material_usage = db('material_usage')->where(['id' => $data['id']])->find();
            db('routine_usage')->where('stock_id',$material_usage['Material_id'])->setInc('number',$material_usage['square_quantity']);

        }
        r_date($material_usage, 200);
    }

    /**
     * 获取费用已选列表
     */
    public function get_reimbursement_list()
    {
        $data = Request::instance()->post();
        //费用报销
        if( $data['type']==1){
            $reimbursement = db('reimbursement')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id'], 'type' => 1])->field('reimbursement_name,money,voucher,created_time,id,status,remake')->select();
        }else{
            $reimbursement = db('reimbursement')->where(['order_id' => $data['order_id'], 'type' =>2])->field('reimbursement_name,money,voucher,created_time,id,status,remake,user_id')->order('status asc')->select();
            foreach ($reimbursement as $k => $item) {
                $reimbursement[$k]['user_id'] = Db::connect(config('database.db2'))->table('app_user')
                    ->where('id',$item['user_id'])
                    ->field('username')
                    ->find()['username'];
            }
        }
        foreach ($reimbursement as $k => $item) {
            $reimbursement[$k]['voucher'] = empty(unserialize($item['voucher']))?[]:unserialize($item['voucher']);
        }

        r_date($reimbursement, 200);
    }

    /**
     * 师傅报销审核
     */
    public function get_Material_To_Reimbursement(Approval $approval)
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            //材料领用
            $reimbursement = db('reimbursement')->where(['id' => $data['id']])->find();
            if ($data['status'] == 1) {
                $my_string = unserialize($reimbursement['voucher']);
                $data['name']=$reimbursement['reimbursement_name'];
                $data['money']=$reimbursement['money'];
                $data['work_wechat_user_id']=$this->us['work_wechat_user_id'];
                if(empty($data['work_wechat_user_id'])){
                    throw new Exception('请联系公司');
                }
                $p         = $approval->Reimbursement($data, $my_string);
                if ($p['errcode'] != 0) {
                    throw new Exception('企业微信提交失败');
                }
                $p=['status' => $data['status'],  'sp_no' => $p['sp_no'],];
            }else{
                $p=['status' => $data['status'], 'remake' => $data['remake']];
            }
            db('reimbursement')->where(['id' => $data['id']])->update($p);
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }


    /*
     * 人工结算
     */
    public function artificial_list()
    {

        $data    = Request::instance()->post();
        $capital = $cap = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->field('class_b,capital_id')->select();
        if (empty($capital)) {
            r_date(null, 300, '数据不存在');
        }

        foreach ($capital as $k => $kl) {
            $reality_artificial  = Db::connect(config('database.db2'))->table('app_user_order_capital')
                ->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')
                ->where('app_user_order_capital.capital_id', $kl['capital_id'])
                ->where('app_user_order_capital.deleted_at', 'null')
                ->field('app_user_order_capital.work_time,app_user_order_capital.personal_price,app_user.username,app_user_order_capital.user_id')
                ->select();
//            echo Db::connect(config('database.db2'))->table('app_user_order_capital')->getLastSql();die;
            $capital[$k]['data'] = $reality_artificial;;
        }
        r_date($capital, 200);


    }


    /*
     * 采购添加
     */
    public function purchase_usage_material(Approval $approval)
    {

        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $validate = new validate\Purchase_usage();
            if (!$validate->check($data)) {
                r_date($validate->getError(), 300);
            }
            if ($data['type'] == 1) {
                $data['work_wechat_user_id']=$this->us['work_wechat_user_id'];
                if(empty($data['work_wechat_user_id'])){
                    throw new Exception('请联系公司');
                }
                $wechatObj_data = $approval->Purchase($data);
                if ($wechatObj_data['errcode']  != 0) {
                    throw new Exception('企业微信提交失败');
                }
                $id = db('purchase_usage')->insertGetId([
                    'stock_name'   => $data['stock_name'],
                    'company'      => $data['company'],
                    'latest_cost'  => $data['latest_cost'],
                    'voucher'      => !empty($data['voucher']) ? serialize(json_decode($data['voucher'], true)) : '',
                    'user_id'      => $this->us['user_id'],
                    'store_id'     => $this->us['store_id'],
                    'created_time' => time(),
                    'remake'       => $data['remake'],
                    'type'         => 1,
                    'number'       => $data['number'],
                    'status'       => 0,
                    'sp_no'        => $wechatObj_data['sp_no'],
                ]);

            } elseif ($data['type'] == 2) {
                $id = db('custom_material')->insertGetId([
                    'stock_name'   => $data['stock_name'],
                    'company'      => $data['company'],
                    'latest_cost'  => $data['latest_cost'],
                    'voucher'      => !empty($data['voucher']) ? serialize(json_decode($data['voucher'], true)) : '',
                    'user_id'      => $this->us['user_id'],
                    'store_id'      => $this->us['store_id'],
                    'remake'       => $data['remake'],
                    'created_time' => time(),
                    'status'       => 0,
                    'number'       => $data['number'],
                ]);
            }

            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }


    }

    /*
    * 采购收货/入库
    */
    public function purchase_usage_Warehousing()
    {
        $data = Request::instance()->post();
        //入库
        $id = db('purchase_usage')->where('id', $data['id'])->update(['status' => 3]);
        if ($id) {
            r_date($id, 200);
        } else {
            r_date(null, 300);
        }

    }

    /*
      * 常规材料直接入库没有收货
      */
    public function routine_usage_Warehousing()
    {
        $data = Request::instance()->post();
        //入库
        $custom = db('stock')
            ->where('id', $data['id'])
            ->find();

        if (empty($custom)) {
            r_date(null, 300, '数据不存在');
        }
        $id = db('routine_usage')->insertGetId([
            'stock_name'   => $custom['stock_name'],
            'stock_id'     => $custom['id'],
            'store_id'     => $this->us['store_id'],
            'company'      => $custom['company'],
            'latest_cost'  => $custom['latest_cost'],
            'user_id'      => $this->us['user_id'],
            'number'       => $data['number'],
            'created_time' => time(),
        ]);
        if ($id) {
            r_date($id, 200);
        } else {
            r_date(null, 400);
        }
    }


}